/**
* ...
* @author Default
* @version 0.1
*/

package org.anivision.plugins {
	import flash.events.IOErrorEvent;
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.net.URLLoader;
	import flash.net.URLRequest;

	public class ScriptLoader extends EventDispatcher{
		
		private var _files:Array = new Array();
		private var _loaded:int = 0;
		private var _name:String;
		private var _script:String = '';
		private var _error:Boolean = false;
		
		public function ScriptLoader(script:*, name) {
			_name = name;
			if ( script is Array )
			{
				_files = script;
			}
			else if ( script is String )
			{
				_files.push(script);
			}
		}
		
		public function load():void
		{
			loadPath(_files[0]);
		}
		
		private function loadPath(path)
		{
			var loader:URLLoader = new URLLoader();
			var request:URLRequest = new URLRequest(path);
			loader.addEventListener(Event.COMPLETE, __onFileLoaded);
			loader.addEventListener(IOErrorEvent.IO_ERROR, __onFileNotLoaded);
			loader.load(request);
		}
		
		private function __onFileNotLoaded(e:Event):void {
			this._error = true;
			var event:IOErrorEvent = new IOErrorEvent(IOErrorEvent.IO_ERROR);
			this.dispatchEvent(event);
		}
		private function __onFileLoaded(e:Event):void {
			_loaded++;
			_script += "\n" + e.target.data;			
			
			if ( _loaded == _files.length )
				this.dispatchEvent(new Event(Event.COMPLETE));
			else if ( _loaded < _files.length )
				loadPath(_files[_loaded]);
		}
		
		public function get code():String {
			return _script;
		}
	}
	
}
